/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <unordered_set>

using namespace std;
//1.哈希表
class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set<ListNode *> myset;
        while(head!=NULL&&head->next!=NULL)
        {
            if (myset.find(head->next)!=myset.end())
            {
                return true;
            }
            else
            {
                myset.insert(head->next);
                head=head->next;
            }
            
        }
        return false;
    }
};

//2.快慢指针
class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode * slow=head;
        ListNode * fast=head;
        while(fast!=NULL&&fast->next!=NULL)
        {
            if(fast->next==slow)
            {
                return true;
            }
            else
            {
                slow=slow->next;
                fast=fast->next->next;
            }
        }
        return false;
    }
};

// 2020.8.12 town
class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode* fast=head;
        ListNode* slow=head;
        while(true){
            if(fast==NULL || fast->next==NULL){
                return false;
            }
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast){
                return true;
            }
        }
        return true;
    }
};